import { colord } from 'colord'
import { set } from 'radash'
import themeConfig from './theme.json'
import { ref } from 'vue'
import { useColorMode } from '@vueuse/core'

const docEle = ref(document.documentElement)
const { isFullscreen, toggle } = useFullscreen(docEle)
const { system, store } = useColorMode({
  emitAuto: true
})

export const useAppStore = defineStore('app-store', {
  state: () => {
    return {
      footerText: import.meta.env.VITE_COPYRIGHT_INFO,
      theme: themeConfig,
      primaryColor: themeConfig.common.primaryColor,
      collapsed: false,
      loadFlag: true,
      showLogo: true,
      showTabs: true,
      showFooter: true,
      showProgress: true,
      showBreadcrumb: true,
      showBreadcrumbIcon: true,
      showWatermark: true,
      showSetting: false,
      transitionAnimation: 'fade',
      layoutMode: 'leftMenu'
    }
  },
  getters: {
    storeColorMode() {
      return store.value
    },
    colorMode() {
      return store.value === 'auto' ? system.value : store.value
    },
    fullScreen() {
      return isFullscreen.value
    }
  },
  actions: {
    // 重置所有设置
    resetAlltheme() {
      this.theme = themeConfig
      this.primaryColor = '#18a058'
      this.collapsed = false
      this.loadFlag = true
      this.showLogo = true
      this.showTabs = true
      this.showFooter = true
      this.showProgress = true
      this.showBreadcrumb = true
      this.showBreadcrumbIcon = true
      this.showWatermark = false
      this.transitionAnimation = 'fade'
      this.layoutMode = 'leftMenu'
      // 重置所有配色
      this.setPrimaryColor(this.primaryColor)
    },
    // 设置主题色
    setPrimaryColor(color) {
      const brightenColor = colord(color).lighten(0.05).toHex()
      const darkenColor = colord(color).darken(0.05).toHex()
      set(this.theme, 'common.primaryColor', color)
      set(this.theme, 'common.primaryColorHover', brightenColor)
      set(this.theme, 'common.primaryColorPressed', darkenColor)
      set(this.theme, 'common.primaryColorSuppl', brightenColor)
    },
    setColorMode(mode) {
      store.value = mode
    },
    // 切换侧边栏收缩
    toggleCollapse() {
      this.collapsed = !this.collapsed
    },
    // 切换全屏
    toggleFullScreen() {
      toggle()
    },
    /**
     * @description: 页面内容重载
     * @param {Number} delay - 延迟毫秒数
     * @return {*}
     */
    async reloadPage(delay = 600) {
      this.loadFlag = false
      await nextTick()
      if (delay) {
        setTimeout(() => {
          this.loadFlag = true
        }, delay)
      } else {
        this.loadFlag = true
      }
    }
  },
  persist: {
    enabled: true,
    strategies: [
      {
        storage: localStorage
      }
    ]
  }
})
